import 'package:flutter/cupertino.dart';
import 'package:tetris/material/material.dart';
import 'dart:ui' as ui;
class MyMaterial extends StatelessWidget {

  final Size widgetSize;
  final Size srcSize;
  final Offset srcOffset;

  const MyMaterial(
      {Key key,
        @required this.widgetSize,
        @required this.srcSize,
        @required this.srcOffset})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      foregroundPainter: _MaterialPainter(  srcOffset, srcSize, GameMaterial.getMaterial(context)),
      child: SizedBox.fromSize(
        size: widgetSize,
      ),
    );
  }
}

class _MaterialPainter extends CustomPainter {
  final Offset offset;
  final Size size;
  Paint _paint = Paint();
  final ui.Image material;

  _MaterialPainter(this.offset, this.size, this.material);

  @override
  void paint(Canvas canvas, Size size) {
    if(offset.dy ==100){
      print("dx===${offset.dx} ,${offset.dy}") ;
    }

    // 获得一个矩形
    final src = Rect.fromLTWH(offset.dx, offset.dy, this.size.width, this.size.height);
    canvas.scale(size.width / this.size.width, size.height / this.size.height);
    // 从 material 资源中 ，取出 第二个参数的矩形范围，绘制到第三个参数代表的矩形中
    canvas.drawImageRect(material, src, Rect.fromLTWH(0, 0, this.size.width, this.size.height), _paint);
  }

  @override
  bool shouldRepaint(_MaterialPainter oldDelegate) {
    return oldDelegate.offset != offset || oldDelegate.size != size;
  }
}
